import React, { useMemo, useState } from 'react';
import {
  Card,
  Form,
  Input,
  DatePicker,
  Button,
  Table,
  Image,
  Space,
  Modal,
  Select,
  InputNumber,
  Switch,
  Tag,
  Pagination,
  message,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  StarOutlined,
  PictureOutlined,
} from '@ant-design/icons';

const { RangePicker } = DatePicker;

export default function ActivityList() {
  // 查询与列表数据（模拟）
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState([
    {
      id: 1001,
      name: '新春促销活动',
      photoQrCode: 'https://dummyimage.com/100x100/1677ff/ffffff&text=QR',
      photoPassword: '1234',
      startTime: '2025-02-01 09:00:00',
      endTime: '2025-02-15 23:59:59',
      createTime: '2025-01-15 10:00:00',
      printNum: 120,
      photoNum: 36,
      cloudPhotoSwitch: 1,
      isDefault: 0,
      isRetain: 0,
      userMachineId: '1,2',
      uploadSwitch: 1,
      electronicSwitch: 0,
      electronicPrice: 0,
    },
    {
      id: 1002,
      name: '设备升级提示',
      photoQrCode: 'https://dummyimage.com/100x100/13c2c2/ffffff&text=QR',
      photoPassword: '',
      startTime: '',
      endTime: '',
      createTime: '2025-02-01 08:00:00',
      printNum: 60,
      photoNum: 18,
      cloudPhotoSwitch: 0,
      isDefault: 1,
      isRetain: 1,
      userMachineId: '3',
      uploadSwitch: 0,
      electronicSwitch: 1,
      electronicPrice: 5,
    },
  ]);

  const [albumModalOpen, setAlbumModalOpen] = useState(false);
  const [albumPage, setAlbumPage] = useState({ pageNum: 1, pageSize: 9, total: 12 });
  const [albumList, setAlbumList] = useState(
    new Array(9).fill(0).map((_, i) => ({ id: i + 1, url: `https://picsum.photos/seed/al${i}/300/200` }))
  );

  const [editModalOpen, setEditModalOpen] = useState(false);
  const [editForm] = Form.useForm();
  const [machineOptions] = useState([
    { label: '机器1', value: 1 },
    { label: '机器2', value: 2 },
    { label: '机器3', value: 3 },
  ]);
  const [editingRow, setEditingRow] = useState(null);

  const columns = useMemo(
    () => [
      {
        title: 'ID',
        dataIndex: 'id',
        width: 120,
        render: (id, row) => (
          <Space>
            <span>{id}</span>
            {row.isDefault === 1 && <span style={{ color: '#ff4d4f' }}>(默认活动)</span>}
          </Space>
        ),
      },
      { title: '活动名称', dataIndex: 'name', width: 160 },
      {
        title: '相册二维码',
        dataIndex: 'photoQrCode',
        width: 140,
        render: (src) => <Image width={100} height={100} src={src} fallback="/vite.svg" />,
      },
      { title: '相册密码', dataIndex: 'photoPassword', width: 120 },
      { title: '开始时间', dataIndex: 'startTime', width: 180 },
      { title: '结束时间', dataIndex: 'endTime', width: 180 },
      { title: '创建时间', dataIndex: 'createTime', width: 180 },
      { title: '打印数量', dataIndex: 'printNum', width: 120 },
      { title: '照片数量', dataIndex: 'photoNum', width: 120 },
      {
        title: '云相册开关',
        dataIndex: 'cloudPhotoSwitch',
        width: 120,
        render: (_, row) => (
          <Switch
            checked={row.cloudPhotoSwitch === 1}
            loading={row._loading}
            onChange={async (checked) => {
              row._loading = true;
              setDataSource((ds) => [...ds]);
              try {
                await new Promise((r) => setTimeout(r, 500));
                row.cloudPhotoSwitch = checked ? 1 : 0;
                message.success('已更新云相册开关');
              } finally {
                row._loading = false;
                setDataSource((ds) => [...ds]);
              }
            }}
          />
        ),
      },
      {
        title: '操作',
        key: 'actions',
        width: 260,
        fixed: 'right',
        render: (_, row) => (
          <Space>
            <Button size="small" icon={<PictureOutlined />} onClick={() => openAlbum(row)}>
              相册
            </Button>
            {row.isRetain !== 1 && (
              <Button size="small" type="primary" icon={<StarOutlined />} onClick={() => handleCollect(row)}>
                收藏
              </Button>
            )}
            <Button size="small" type="dashed" icon={<EditOutlined />} onClick={() => openEdit(row)}>
              编辑
            </Button>
            {row.isDefault !== 1 && (
              <Button size="small" danger icon={<DeleteOutlined />} onClick={() => handleDelete(row)}>
                删除
              </Button>
            )}
          </Space>
        ),
      },
    ],
    [dataSource]
  );

  const handleSearch = async () => {
    setLoading(true);
    try {
      await new Promise((r) => setTimeout(r, 300));
      // 这里可根据 form.getFieldsValue() 过滤数据源，当前仅模拟
    } finally {
      setLoading(false);
    }
  };

  const handleReset = () => {
    form.resetFields();
    handleSearch();
  };

  function handleDelete(row) {
    Modal.confirm({
      title: '删除确认',
      content: '是否删除该活动？',
      onOk: async () => {
        message.loading({ content: '删除中...', key: 'delAct' });
        await new Promise((r) => setTimeout(r, 500));
        setDataSource((prev) => prev.filter((it) => it.id !== row.id));
        message.success({ content: '删除成功', key: 'delAct' });
      },
    });
  }

  function handleCollect(row) {
    Modal.confirm({
      title: '收藏确认',
      content: '是否将该活动加入收藏？',
      onOk: async () => {
        message.loading({ content: '收藏中...', key: 'collectAct' });
        await new Promise((r) => setTimeout(r, 500));
        setDataSource((prev) => prev.map((it) => (it.id === row.id ? { ...it, isRetain: 1 } : it)));
        message.success({ content: '收藏成功', key: 'collectAct' });
      },
    });
  }

  function openAlbum(row) {
    // 模拟拉取相册数据
    setAlbumPage((p) => ({ ...p, activityId: row.id, pageNum: 1 }));
    setAlbumList(new Array(9).fill(0).map((_, i) => ({ id: i + 1, url: `https://picsum.photos/seed/${row.id}-${i}/300/200` })));
    setAlbumModalOpen(true);
  }

  function changeAlbumPage(page) {
    setAlbumPage((p) => ({ ...p, pageNum: page }));
    // 模拟翻页
    setAlbumList(new Array(9).fill(0).map((_, i) => ({ id: i + 1 + (page - 1) * 9, url: `https://picsum.photos/seed/p${page}-${i}/300/200` })));
  }

  function openEdit(row) {
    setEditingRow(row || null);
    const machines = (row?.userMachineId || '').split(',').filter(Boolean).map((v) => Number(v));
    editForm.setFieldsValue({
      id: row?.id,
      name: row?.name,
      dateRange: row?.startTime && row?.endTime ? [row.startTime, row.endTime] : undefined,
      machineArr: machines,
      photoPassword: row?.photoPassword,
      uploadSwitch: row?.uploadSwitch === 1,
      cloudPhotoSwitch: row?.cloudPhotoSwitch === 1,
      electronicSwitch: row?.electronicSwitch === 1,
      electronicPrice: row?.electronicPrice || 0,
    });
    setEditModalOpen(true);
  }

  async function submitEdit() {
    try {
      const values = await editForm.validateFields();
      // 组装提交数据
      const payload = {
        id: values.id,
        name: values.name,
        startTime: values.dateRange?.[0],
        endTime: values.dateRange?.[1],
        userMachineId: (values.machineArr || []).join(','),
        photoPassword: values.photoPassword,
        uploadSwitch: values.uploadSwitch ? 1 : 0,
        cloudPhotoSwitch: values.cloudPhotoSwitch ? 1 : 0,
        electronicSwitch: values.electronicSwitch ? 1 : 0,
        electronicPrice: Number(values.electronicPrice || 0),
      };
      message.loading({ content: '提交中...', key: 'editAct' });
      await new Promise((r) => setTimeout(r, 600));
      setDataSource((prev) => {
        const exist = prev.some((it) => it.id === payload.id);
        if (exist) {
          return prev.map((it) => (it.id === payload.id ? { ...it, ...payload } : it));
        }
        return [{
          ...payload,
          createTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
          printNum: 0,
          photoNum: 0,
          isDefault: 0,
          isRetain: 0,
          photoQrCode: 'https://dummyimage.com/100x100/722ed1/ffffff&text=QR',
        }, ...prev];
      });
      message.success({ content: '提交成功', key: 'editAct' });
      setEditModalOpen(false);
      editForm.resetFields();
    } catch (e) {
      // 校验失败忽略
    }
  }

  return (
    <Space direction="vertical" size={16} style={{ width: '100%' }}>
      <Card title="活动管理 - 活动列表" extra={<Button type="primary" icon={<PlusOutlined />} onClick={() => openEdit(null)}>新增活动</Button>}>
        <Form form={form} layout="inline" onFinish={handleSearch}>
          <Form.Item name="activityName">
            <Input allowClear placeholder="活动名称" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item name="id">
            <Input allowClear placeholder="活动ID" style={{ width: 150 }} />
          </Form.Item>
          <Form.Item name="activityRange">
            <RangePicker showTime placeholder={["活动开始时间", "活动结束时间"]} />
          </Form.Item>
          <Form.Item name="createRange">
            <RangePicker showTime placeholder={["创建开始时间", "创建结束时间"]} />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">查询</Button>
              <Button onClick={handleReset}>重置</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card>
        <Table
          rowKey="id"
          loading={loading}
          dataSource={dataSource}
          columns={columns}
          scroll={{ x: 1200 }}
          pagination={{ pageSize: 10 }}
        />
      </Card>

      <Modal
        title="活动相册"
        open={albumModalOpen}
        width={1100}
        onCancel={() => setAlbumModalOpen(false)}
        onOk={() => setAlbumModalOpen(false)}
      >
        <Space wrap>
          {albumList.length <= 0 ? (
            <Tag color="default">暂无相册内容</Tag>
          ) : (
            albumList.map((item) => (
              <Image key={item.id} width={300} height={200} src={item.url} />
            ))
          )}
        </Space>
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 16 }}>
          <Pagination
            current={albumPage.pageNum}
            pageSize={albumPage.pageSize}
            total={albumPage.total}
            onChange={changeAlbumPage}
          />
        </div>
      </Modal>

      <Modal
        title={editingRow ? '编辑活动' : '新增活动'}
        open={editModalOpen}
        width={540}
        onCancel={() => setEditModalOpen(false)}
        onOk={submitEdit}
      >
        <Form form={editForm} layout="vertical">
          <Form.Item name="id" label="活动ID">
            <Input placeholder="不填将自动生成" />
          </Form.Item>
          <Form.Item name="name" label="活动名称" rules={[{ required: true, message: '请输入活动名称' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="dateRange" label="活动时间范围" rules={[{ required: true, message: '请选择活动时间范围' }]}>
            <RangePicker showTime />
          </Form.Item>
          <Form.Item name="machineArr" label="选择机器" rules={[{ required: true, message: '请选择机器' }]}>
            <Select mode="multiple" allowClear options={machineOptions} placeholder="可筛选" maxTagCount={1} />
          </Form.Item>
          <Form.Item name="photoPassword" label="相册密码">
            <Input.Password placeholder="可留空" />
          </Form.Item>
          <Form.Item label="上传开关" name="uploadSwitch" valuePropName="checked">
            <Switch />
          </Form.Item>
          <Form.Item label="云相册开关" name="cloudPhotoSwitch" valuePropName="checked">
            <Switch />
          </Form.Item>
          <Form.Item label="电子价签开关" name="electronicSwitch" valuePropName="checked">
            <Switch />
          </Form.Item>
          <Form.Item label="电子价签价格" name="electronicPrice">
            <InputNumber min={0} style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      </Modal>
    </Space>
  );
}